package com.mediacloud.app.newsmodule.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Parcelable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.chinamcloud.collect.AcquisitionManager
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager.Companion.getInstance
import com.jaeger.library.StatusBarUtil
import com.mediacloud.app.appfactory.cache.UserRecommend
import com.mediacloud.app.assembly.clickutils.NoDoubleClickUtils
import com.mediacloud.app.assembly.util.FileFormatUtils
import com.mediacloud.app.assembly.util.StringUtils
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.util.toastCenter
import com.mediacloud.app.cloud.qrcodescan.getOriginImageForThumbnailImage
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.interfaces.IPermissionsAgree
import com.mediacloud.app.model.interfaces.PermissionUtil.invokeStoragePermission
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleItemReciver
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.GroupPhotoDataReciver.PhotoItem
import com.mediacloud.app.model.news.ReadDataReciver
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.model.AddHistoryParamsData
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter.TimeoutCallback
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics
import com.mediacloud.app.newsmodule.utils.Addintegral
import com.mediacloud.app.newsmodule.utils.CollectionController
import com.mediacloud.app.newsmodule.utils.DomainUtil
import com.mediacloud.app.newsmodule.utils.HistoryInvoker
import com.mediacloud.app.newsmodule.utils.LoginUtils
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker
import com.mediacloud.app.newsmodule.view.BaseSpiderViewX
import com.mediacloud.app.newsmodule.view.HackyViewPager
import com.mediacloud.app.newsmodule.view.PictureViewX
import com.mediacloud.app.reslib.analysis.AnalysisUtils
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.ServerAppConfigInfo.NavigateBarStyle
import com.mediacloud.app.reslib.enums.TitileType
import com.mediacloud.app.user.model.UserInfo
import com.mediacloud.app.util.ClickUtils
import com.model.PhotoInfo
import org.json.JSONArray
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.Date

/**
 * 图集文稿转换成kotlin
 * */
class ImageNewsDetailActivity : StyleSetActivity(), DataInvokeCallBack<ArticleItemReciver> {
    private var isImgNewsJump = false
    private var downloadLayout: RelativeLayout? = null
    private var downloadBack: ImageView? = null
    private var downloadIco: ImageView? = null
    private var downloadNumb: TextView? = null
    private var text_editor: TextView? = null
    private var text_source: TextView? = null
    private var tv_look_origin_logo: TextView? = null
    private var mViewPager: ViewPager? = null
    private val mPhotoUrls: ArrayList<PhotoInfo>? = ArrayList()
    protected var photos: MutableList<PhotoItem>? = null
    protected var isDisposed = false
    var tvAuthor: TextView? = null
    var tvPlayCount: TextView? = null
    var tvPublishData: TextView? = null

    protected var bottomTextDesLayout: LinearLayout? = null
    protected var photoGroupRootView: RelativeLayout? = null
    protected var photoContent: FrameLayout? = null
    protected var bottomRelativeView: View? = null
    protected var imageTitle: TextView? = null
    protected var imageDes: TextView? = null
    var sewsDetailInvoker: NewsDetailInvoker? = null
    protected var mTitileBar: RelativeLayout? = null
    var spiderView: BaseSpiderViewX? = null
    var pictureViewXHashMap: HashMap<Int, PictureViewX>? = HashMap()

    var mLine: View? = null
    var hideImageTitle = false

    private var bottomOpratateLayout: LinearLayout? = null
    private var isLocalSpinder = true
    var mTyReportStartTime: Long = 0
    var mTyReportEndTime: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val lp = window.attributes
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                lp.layoutInDisplayCutoutMode =
                    WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            }
            window.attributes = lp
            window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.BLACK
            window.navigationBarColor = Color.BLACK
        }
        StatusBarUtil.setDarkMode(this)
        //是不是图文新闻跳转的
        isImgNewsJump = intent.getBooleanExtra("isImgNewsJump", false)
        catalogItem = intent.getParcelableExtra("catalog")
        articleItem = intent.getParcelableExtra("data")
        try {
            if (catalogItem == null) catalogItem = CatalogItem()
            catalogItem.catalog_type = intent.getStringExtra("category")
            catalogItem.catid = intent.getStringExtra("navigate_id")
            if (articleItem == null) {
                articleItem = ArticleItem()
                articleItem.id = (intent.getStringExtra("article_id")?.toLong())!!
                articleItem.summary = intent.getStringExtra("summary")
                articleItem.title = (intent.getStringExtra("title"))
                articleItem.url = (intent.getStringExtra("url"))
                articleItem.isAdvertisement = intent.getIntExtra("isAdvertisement", 0)
                articleItem.isBarrage = intent.getIntExtra("isBarrage", 0)
                articleItem.referSourceID = intent.getStringExtra("ReferSourceID")
                articleItem.isComment = intent.getStringExtra("isComment")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (articleItem != null) {
            isLocalSpinder = articleItem.isLocalSpinder
            sendExposureEvent()
        }
        historyInvoker = HistoryInvoker()
        hideImageTitle = intent.getBooleanExtra("hideImageTitle", false)
        sewsDetailInvoker = NewsDetailInvoker(this)
        initView()
        loadImageNewsDetail()
        decideTitileBarStyle()
        setTitle("")
        // setNewsTitle();
//        if (!isImgNewsJump)
//            showStateView(TYPE_LOADING, false);
        onPageStart()
        showPageTransition()
        mTitileBar.setBackgroundColor(Color.TRANSPARENT)
        val lp = mTitileBar.layoutParams as ViewGroup.MarginLayoutParams
        lp.topMargin = StatusBarUtil.getStatusBarHeight(this)
        mTitileBar.layoutParams = lp
        if (articleItem != null && articleItem.localShareType == -1) {
            if (mTitlebar_More != null) {
                mTitlebar_More.visibility = View.GONE
            }
            if (bottomOpratateLayout != null) {
                bottomOpratateLayout!!.visibility = View.GONE
            }
            if (bottomRelativeView != null) {
                bottomRelativeView!!.visibility = View.GONE
            }
        }
        photoGroupRootView!!.setBackgroundColor(Color.BLACK)
        tvLetmeSay.setTextColor(Color.parseColor("#FF999999"))
        if (bottomRelativeView!!.visibility == View.VISIBLE) { //从文稿进入不添加历史记录
            addHistory()
        }

        //设置笑脸颜色白色
        ivFace.setImageResource(R.drawable.icon_face)
        if (retryTips != null) {
            retryTips.setOnClickListener {
                if (currentState != TYPE_LOADING) {
                    showStateView(TYPE_LOADING, false)
                    loadImageNewsDetail()
                    decideTitileBarStyle()
                    setTitle("")
                    // setNewsTitle();
                    //        if (!isImgNewsJump)
                    //            showStateView(TYPE_LOADING, false);
                    onPageStart()
                    showPageTransition()
                    mTitileBar.setBackgroundColor(Color.TRANSPARENT)
                    val lp = mTitileBar.layoutParams as ViewGroup.MarginLayoutParams
                    lp.topMargin =
                        StatusBarUtil.getStatusBarHeight(this@ImageNewsDetailActivity)
                    mTitileBar.layoutParams = lp
                    if (articleItem != null && articleItem.localShareType == -1) {
                        if (mTitlebar_More != null) {
                            mTitlebar_More.visibility = View.GONE
                        }
                        if (bottomOpratateLayout != null) {
                            bottomOpratateLayout!!.visibility = View.GONE
                        }
                        if (bottomRelativeView != null) {
                            bottomRelativeView!!.visibility = View.GONE
                        }
                    }
                    photoGroupRootView!!.setBackgroundColor(Color.BLACK)
                    tvLetmeSay.setTextColor(Color.parseColor("#FF999999"))
                    if (bottomRelativeView!!.visibility == View.VISIBLE) { //从文稿进入不添加历史记录
                        addHistory()
                    }

                    //设置笑脸颜色白色
                    ivFace.setImageResource(R.drawable.icon_face)
                }
            }
        }
    }


    override fun setWhiteBottomButton() {
        isWhiteColor = true
    }

    override fun getContent_show_top_color(): String? {
        return "#FFFFFF"
    }

    override fun openTitleBarSetting(): Boolean {
        return true
    }


    override fun getStatusBarColor(): Int {
        return Color.TRANSPARENT
    }

    override fun getFitSystemWindow(): Boolean {
        return false
    }

    private var historyInvoker: HistoryInvoker? = null

    private fun addHistory() {
        val paramsData = AddHistoryParamsData()
        paramsData.source = CollectionController.convertToSource(catalogItem)
        if (articleItem.getId() > 0) {
            paramsData.source_id = articleItem.getId()
        } else {
            if (!TextUtils.isEmpty(articleItem.referTarget)) {
                try {
                    paramsData.source_id = articleItem.referTarget.toLong()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        paramsData.summary = articleItem.summary
        paramsData.title = articleItem.getTitle()
        paramsData.type = articleItem.getType().toString() + ""
        paramsData.url = articleItem.getUrl()
        paramsData.logo = articleItem.logo
        paramsData.publishdate_format = articleItem.publishdate_format
        paramsData.isFromEpaper = if (articleItem.isEPaper) "1" else "0"
        paramsData.logoImgSize = articleItem.logoImgSize
        historyInvoker!!.addHistory(UserInfo.getUserInfo(this).userid, paramsData, null)
    }


    var readStatusInvoker: ReadStatusInvoker? = null

    fun readStatus() {
        readStatusInvoker = ReadStatusInvoker(object : DataInvokeCallBack<ReadDataReciver?> {
            override fun success(data: ReadDataReciver?) {
                if (isFinishing || isDestroyed) {
                    return
                }
                AnalysisUtils.readsAnalysis(
                    applicationContext,
                    articleItem,
                    data?.virtualIncrement!!
                )
            }

            override fun fault(data: Any) {
                if (isFinishing || isDestroyed) {
                    return
                }
                AnalysisUtils.readsAnalysis(
                    applicationContext,
                    articleItem,
                    AnalysisUtils.DefaultVirtualIncrement
                )
            }
        })
        readStatusInvoker!!.readStatistics(articleItem.getId().toString() + "", 1)
    }


    protected fun setNewsTitle() {
        val base = serverAppConfigInfo.getBase()
        if (base == TitileType.FRAME) {
            setFrameTypeTitle()
        } else if (base == TitileType.NAVIGATE) {
            setTitle(if (catalogItem != null) catalogItem.catname else "")
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(if (articleItem != null) articleItem.getTitle() else "")
        } else if (base == TitileType.NOTITLE) {
            setTitle("")
        }
    }


    override fun needLoadTopSecondBgSkin(): Boolean {
        return super.subClassgetNeedTopSecondBgSkin()
    }

    override fun getNewsDetailNavigateBarStyle(): NavigateBarStyle? {
        return AppFactoryGlobalConfig.getAppServerConfigInfo(this).photoNewsBar
    }


    protected fun initView() {
        mTitlebar_More = findViewById(R.id.mTitlebar_More)
        spiderView = Utility.findViewById(mRootView, R.id.spiderView)
        rlayout_back = Utility.findViewById(mRootView, R.id.rlayout_back)
        bottomTextDesLayout = findViewById(R.id.bottomTextDesLayout)
        photoGroupRootView = findViewById(R.id.photoGroupRootView)
        text_editor = findViewById(R.id.text_editor)
        text_source = findViewById(R.id.text_source)
        imageTitle = findViewById(R.id.imageTitle)
        mTitileBar = findViewById<RelativeLayout>(R.id.rlTitleBar)
        if (hideImageTitle) imageTitle?.setVisibility(View.INVISIBLE)
        imageDes = findViewById(R.id.imageDes)
        photoContent = findViewById(R.id.photoContent)
        bottomRelativeView = findViewById(R.id.relative_bottom)
        bottomOpratateLayout = findViewById(R.id.linear_news_bottom_back_bar)
        mViewPager = HackyViewPager(this)
        photoContent?.addView(
            mViewPager,
            FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        )
        val lp = photoContent?.getLayoutParams() as ViewGroup.MarginLayoutParams
        lp.topMargin = StatusBarUtil.getStatusBarHeight(this)
        photoContent?.setLayoutParams(lp)

        // mViewPager.setFitsSystemWindows(true);
        bottomBarLayout.setBackgroundColor(Color.TRANSPARENT)
        mLine = findViewById(R.id.photo_line)
        mLine?.setVisibility(View.GONE)
        mRootView.setBackgroundColor(Color.BLACK)
        intDownLoadView()
        //组图的 我来说两句 评论框背景是黑色的
//        Drawable drawable = tvLetmeSay.getBackground().mutate();
//        GradientDrawable gradientDrawable = (GradientDrawable) drawable;
//        gradientDrawable.setColor(Color.parseColor("#26F7F7F7"));
        val drawable = ivFace.drawable
        drawable.setTint(Color.WHITE)
        ivFace.setImageDrawable(drawable)
        tvLetmeSay.background = null
        tvLetmeSay.setBackgroundColor(ContextCompat.getColor(this, R.color.c_303030))
        tvLetmeSay.hint = "我来说几句"
        tvPlayCount = findViewById<TextView>(R.id.tvPlayCount)
        tvAuthor = findViewById(R.id.tvAuthor)
        tvPublishData = findViewById<TextView>(R.id.tvPublishData)
        setCommentPhotoColor()
        findViewById<View>(R.id.mTop_back).setOnClickListener { finish() }
        val linkedHashSet =
            AppFactoryGlobalConfig.getAppServerConfigInfo(this).newsDetailConfig.linkedHashSet
        if (!linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !linkedHashSet.contains(
                NewsDetailStyleConfig.SHARE_BUTTON
            )
        ) {
            mTitlebar_More.visibility = View.GONE
        } else {
            mTitlebar_More.visibility = View.VISIBLE
        }
        mTitlebar_More.setOnClickListener { shareWrap.show(mRootView) }
    }

    /* @Override
    protected void showLikeButtonWithConfig(boolean show) {
        super.showLikeButtonWithConfig(show);
    }*/

    /* @Override
    protected void showLikeButtonWithConfig(boolean show) {
        super.showLikeButtonWithConfig(show);
    }*/
    override fun showStateView(type: String?, forceDefault: Boolean) {
        super.showStateView(type, forceDefault)
    }

    /**
     * 图片下载相关
     */
    protected fun intDownLoadView() {
        downloadLayout = findViewById(R.id.downloadLayout)
        downloadNumb = findViewById(R.id.downloadNumb)
        tv_look_origin_logo = findViewById(R.id.tv_look_origin_logo)
        downloadBack = findViewById(R.id.downloadBack)
        downloadBack?.setOnClickListener(View.OnClickListener { finish() })
        tv_look_origin_logo?.setOnClickListener(View.OnClickListener { v ->
            getInstance().app_jhapp_content_detail_interact("查看原图", "", "", articleItem)
            ClickUtils.delayClickable(v)
            if (mViewPager != null && mPhotoUrls != null && mPhotoUrls.size > 0 && mViewPager!!.currentItem < mPhotoUrls.size) {
                if (!mPhotoUrls[mViewPager!!.currentItem].isLocalOriginLogo) {
                    mPhotoUrls[mViewPager!!.currentItem].isLocalOriginLogo = true
                    pictureViewXHashMap!![mViewPager!!.currentItem]!!.setImageURL(
                        mPhotoUrls[mViewPager!!.currentItem].logo,
                        false
                    )
                    tv_look_origin_logo?.setVisibility(View.GONE)
                }
            }
        })
        downloadIco = findViewById<ImageView>(R.id.downloadIco)
        downloadIco?.setOnClickListener(View.OnClickListener {
            getInstance().app_jhapp_content_detail_interact("下载", "", "", articleItem)
            if (NoDoubleClickUtils.isDoubleClick()) {
                return@OnClickListener
            }
            invokeStoragePermission(this@ImageNewsDetailActivity, object : IPermissionsAgree {
                override fun onAgree() {
                    SaveImage().execute(mPhotoUrls!![mViewPager!!.currentItem].logo)
                    if (photos != null && !photos!!.isEmpty() && mViewPager != null) {
                        val pictureName =
                            mViewPager!!.currentItem.toString() + photos!![mViewPager!!.currentItem].name + mViewPager!!.currentItem
                        //TyReportManager.getInstance().save_picture(pictureName, org.xutils.common.util.MD5.md5(catalogItem.getCatname()), catalogItem.getCatname()+"详情页");
                    }
                }

                override fun onRefuse() {}
                override fun hasPermissions() {
                    SaveImage().execute(mPhotoUrls!![mViewPager!!.currentItem].logo)
                    if (photos != null && !photos!!.isEmpty() && mViewPager != null) {
                        val pictureName =
                            mViewPager!!.currentItem.toString() + photos!![mViewPager!!.currentItem].name + mViewPager!!.currentItem
                        //TyReportManager.getInstance().save_picture(pictureName, org.xutils.common.util.MD5.md5(catalogItem.getCatname()), catalogItem.getCatname()+"详情页");
                    }
                }
            })
        })
    }


    protected fun decideTitileBarStyle() {
        if (isShowComment(articleItem)) {
            showCommentRelativeView(true)
        } else {
            showCommentRelativeView(false)
        }
    }
//20230110 等待下次版本更新，本次先关闭优化
//    @Override
//    protected int getBottemBarColor() {
//        return Color.BLACK;
//    }

    //20230110 等待下次版本更新，本次先关闭优化
    //    @Override
    //    protected int getBottemBarColor() {
    //        return Color.BLACK;
    //    }
    fun loadImageNewsDetail() {
        if (!TextUtils.isEmpty(articleItem.real_title)) {
            imageTitle!!.text = articleItem.real_title
        } else {
            if (!TextUtils.isEmpty(articleItem.getTitle())) {
                imageTitle!!.text = articleItem.getTitle()
            } else {
                imageTitle!!.text = articleItem.summary
            }
        }
        imageTitle!!.paint.isFakeBoldText = true
        //现在屏掉直接设置详情 从外面把id给进来的时候    重新去取一次详情  主要是有些搜索的地方要用到
        val navigate_id = catalogItem.catid
        if (!isImgNewsJump) {
            sewsDetailInvoker!!.getArticleById("" + articleItem.getId(), navigate_id)
        } else {
            showCollectWithConfig(false)
            showShareWithConfig(false)
            showCommentButtonWithConfig(false)
            showLikeButtonWithConfig(false)
            setImages(articleItem)
            // mTitlebar_MoreContainer.setVisibility(View.GONE);
            closeStateView()
            val index = intent.getIntExtra("index", 0)
            if (index > 0 && index < mPhotoUrls!!.size) {
                mViewPager!!.currentItem = index
                updateLookOriginLogoUI(index)
            } else {
                updateLookOriginLogoUI(0)
            }
            if (true /*"zgjh".equals(AppFactoryGlobalConfig.getAppServerConfigInfo(this).code_method)*/) {
                if (articleItem.spider != null) {
                    spiderView!!.spiderAuthor.setTextColor(Color.WHITE)
                    spiderView!!.setDate(articleItem)
                    if (!isLocalSpinder) {
                        spiderView!!.visibility = View.GONE
                    }
                }
                tvPlayCount?.setText(StringUtils.toTenThousand(articleItem.hitCount_format) + "浏览")
                if (TextUtils.isEmpty(articleItem.getAuthor())) {
                    tvAuthor!!.visibility = View.GONE
                } else {
                    tvAuthor!!.visibility = View.VISIBLE
                    tvAuthor!!.text = articleItem.getAuthor()
                }
                tvPublishData?.setText(articleItem.publishdate_format)
            } else {
                findViewById<View>(R.id.layout_author).visibility = View.GONE
            }
        }
    }


    protected fun setImages(item: ArticleItem) {
        closeStateView()
        try {
            photos = ArrayList()
            val jsonArray = JSONArray(item.image)
            if (jsonArray.length() == 0) {
                mPhotoUrls!!.add(PhotoInfo())
                val photoItem = PhotoItem()
                photoItem.image = ""
                photoItem.thumb = ""
                photoItem.note = ""
                photos?.add(photoItem)
            }
            for (i in 0 until jsonArray.length()) {
                val photoItem = PhotoItem()
                val jsonObject = jsonArray.optJSONObject(i)
                val url = getOriginImageForThumbnailImage(jsonObject.optString("src", ""))
                val note = jsonObject.optString("info", item.getTitle())
                photoItem.image = url
                photoItem.thumb = url
                photoItem.note = note
                photos?.add(photoItem)
                mPhotoUrls!!.add(PhotoInfo(url))
            }
        } catch (e: Exception) {
            e.printStackTrace()
            //			Log.w(TAG, e.getMessage());
            if (mPhotoUrls!!.size == 0) {
                mPhotoUrls.add(PhotoInfo())
            }
        }
        mViewPager!!.adapter = SamplePagerAdapter(mPhotoUrls)
        mViewPager!!.offscreenPageLimit = mPhotoUrls!!.size
        //	mViewPager.setOffscreenPageLimit(mPhotoUrls.size());
        mViewPager!!.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                updateLookOriginLogoUI(position)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
        updateLookOriginLogoUI(0)
    }


    /**
     * 更新查看原图 UI
     *
     * @param position 页码下标
     */
    fun updateLookOriginLogoUI(position: Int) {
        if (mViewPager != null && mPhotoUrls != null && mPhotoUrls.size > 0 && position < mPhotoUrls.size) {
            /*if (mPhotoUrls.get(position).isLocalOriginLogo) {
                tv_look_origin_logo.setVisibility(View.GONE);
            } else {
                tv_look_origin_logo.setVisibility(View.VISIBLE);
            }*/
            tv_look_origin_logo!!.visibility = View.VISIBLE
        }
    }

    private inner class SamplePagerAdapter(private val urls: ArrayList<PhotoInfo>?) :
        PagerAdapter() {
        private val urlsSize: Int
        private var mPosition = 0
        var hideNote = false

        init {
            urlsSize = urls!!.size
        }

        override fun getCount(): Int {
            return urlsSize
        }

        override fun instantiateItem(container: ViewGroup, position: Int): View {
            if (position >= urlsSize) {
                return PictureViewX(container.context)
            }
            val pictureViewX = PictureViewX(container.context)
            pictureViewX.id = View.generateViewId()
            if (!isImgNewsJump) {
                pictureViewX.mAttacher.setOnViewTapListener { view, x, y ->
                    hideNote = !hideNote
                    if (hideNote) {
                        imageTitle?.setVisibility(View.GONE)
                        mLine?.setVisibility(View.GONE)
                        //                        if (articleItem!=null&&articleItem.getLocalShareType()==-1) {
                        bottomOpratateLayout?.setVisibility(View.GONE)
                        bottomRelativeView?.setVisibility(View.INVISIBLE)
                        //                        }else{
                        //                            bottomRelativeView.setVisibility(View.VISIBLE);
                        //                            bottomOpratateLayout.setVisibility(View.VISIBLE);
                        //                        }
                        if (mTitlebar_More != null) {
                            mTitlebar_More.setVisibility(View.GONE)
                        }
                        if (spiderView != null) {
                            spiderView?.setVisibility(View.GONE)
                        }
                        bottomTextDesLayout?.setVisibility(View.GONE)
                        downloadLayout?.setVisibility(View.VISIBLE)
                    } else {
                        mLine?.setVisibility(View.GONE)
                        imageTitle?.setVisibility(View.VISIBLE)
                        if (articleItem != null && articleItem.getLocalShareType() == -1) {
                            bottomOpratateLayout?.setVisibility(View.GONE)
                            bottomRelativeView?.setVisibility(View.INVISIBLE)
                            if (mTitlebar_More != null) {
                                mTitlebar_More.setVisibility(View.GONE)
                            }
                            if (spiderView != null) {
                                spiderView?.setVisibility(View.GONE)
                            }
                        } else {
                            if (mTitlebar_More != null) {
                                mTitlebar_More.setVisibility(View.VISIBLE)
                            }
                            if (spiderView != null) {
                                spiderView?.setVisibility(View.VISIBLE)
                            }
                            bottomOpratateLayout?.setVisibility(View.VISIBLE)
                            bottomRelativeView?.setVisibility(View.VISIBLE)
                        }
                        bottomTextDesLayout?.setVisibility(View.VISIBLE)
                        downloadLayout?.setVisibility(View.GONE)
                    }
                }
            } else {
                spiderView?.setVisibility(View.GONE)
                imageTitle?.setVisibility(View.GONE)
                downloadLayout?.setVisibility(View.VISIBLE)
                mLine?.setVisibility(View.GONE)
                bottomOpratateLayout?.setVisibility(View.GONE)
                bottomRelativeView?.setVisibility(View.GONE)
                bottomTextDesLayout?.setVisibility(View.GONE)
            }
            pictureViewX.layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            if (urls!![position].isLocalOriginLogo) {
                pictureViewX.setImageURL(urls[position].logo)
            } else {
                pictureViewX.setThumbnailImageURL(urls[position].logo)
            }
            container.addView(pictureViewX, 0)
            pictureViewXHashMap?.put(position, pictureViewX)
            return pictureViewX
        }

        override fun setPrimaryItem(container: View, position: Int, `object`: Any) {
            if (photos?.size == 0) return
            val mainColor: Int = serverAppConfigInfo.getMainColor()
            //			float fontSize=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, getResources().getDisplayMetrics());
            val fontSize: Float = getResources().getDimension(R.dimen.dimen17)
            val fontSize2: Float = getResources().getDimension(R.dimen.dimen17)
            val spannableString =
                SpannableString((position + 1).toString() + "/" + urlsSize) /*+ "  "+articleItem.getTitle())*/
            val focusTextColor = ForegroundColorSpan(Color.parseColor("#D43D3D"))
            spannableString.setSpan(
                focusTextColor,
                0,
                if (position >= 9) 2 else 1,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            //            spannableString.setSpan(new AbsoluteSizeSpan((int) fontSize), 0, position >= 9 ? 2 : 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//
//            spannableString.setSpan(new AbsoluteSizeSpan((int) fontSize2), position >= 9 ? 2 : 1, position >= 9 ? 2 : 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            imageTitle?.setText(spannableString)
            if (!TextUtils.isEmpty(articleItem.getReal_title())) {
                imageTitle?.append("   " + articleItem.getReal_title())
            } else {
                imageTitle?.append("   " + articleItem.getTitle())
            }
            downloadNumb?.setText(spannableString)
            mPosition = position
            var note: String = photos?.get(position)?.getNote()!!
            if (TextUtils.isEmpty(note) && articleItem != null) note = articleItem.getTitle()
            imageDes?.setText(note)
            if (articleItem != null) {
                if (!TextUtils.isEmpty(articleItem.Author) && "null" != articleItem.Author) {
                    text_editor?.setText("责编：" + articleItem.Author)
                }
                if (!TextUtils.isEmpty(articleItem.getReferName()) && "null" != articleItem.getReferName()) {
                    text_source?.setText("来源：" + articleItem.getReferName())
                }
            }
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view === `object`
        }

        //		public int getCurrentPosition() {
        //			return mPosition;
        //		}
        override fun saveState(): Parcelable? {
            val parcelable = super.saveState()
            if (parcelable is Bundle) {
                parcelable.putParcelableArray("states", null)
            }
            return parcelable
        }
    }

    override fun onDestroy() {
        if (articleItem != null && mTyReportStartTime > 0) {
            mTyReportEndTime = System.currentTimeMillis()
        }
        CDPTrackReportManager.getInstance().NewsContentDetailView(articleItem,(System.currentTimeMillis()-inTime)/1000)

        if (pictureViewXHashMap != null) {
            pictureViewXHashMap!!.clear()
        }
        isDisposed = true
        if (sewsDetailInvoker != null) {
            sewsDetailInvoker!!.destory()
        }
        if (readStatusInvoker != null) readStatusInvoker!!.destory()
        readStatusInvoker = null
        if (photos != null) photos!!.clear()
        sewsDetailInvoker = null
        super.onDestroy()
        catalogItem = null
        articleItem = null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        super.onActivityResult(requestCode, resultCode, intent)
    }


    override fun getLayoutResID(): Int {
        return R.layout.activity_photonews_detail
    }


    protected fun intoLogin(context: Context?) {
        //     ToastUtil.show(context, R.string.please_login);
//        Intent intent = new Intent();
//        intent.setClassName(context, ModuleReferenceConfig.LoginActivity);
//        context.startActivity(intent);
        LoginUtils.request_source = "图集"
        LoginUtils.invokeLogin(context)
    }

    override fun success(data: ArticleItemReciver?) {
        if (isFinishing || isDestroyed) {
            return
        }
        if (data?.state!! && data.articleItem != null) {
            mTyReportStartTime = System.currentTimeMillis()
            mTyReportEndTime = mTyReportStartTime
            if (articleItem.fromComponent != 1) // setNewsTitle();
                articleItem = data.articleItem
            shareWrap.init(articleItem, catalogItem)
            if (true /*"zgjh".equals(AppFactoryGlobalConfig.getAppServerConfigInfo(this).code_method)*/) {
                if (articleItem.spider != null) {
                    val spiderView = findViewById<BaseSpiderViewX>(R.id.spiderView)
                    spiderView.spiderAuthor.setTextColor(Color.WHITE)
                    spiderView.setDate(articleItem)
                    if (!isLocalSpinder) {
                        spiderView.visibility = View.GONE
                    }
                }
                tvPlayCount?.setText(StringUtils.toTenThousand(articleItem.hitCount_format) + "浏览")
                //                tvPlayCount.setText(articleItem.getHitCount_format() + "浏览");
                if (TextUtils.isEmpty(articleItem.getAuthor())) {
                    tvAuthor!!.visibility = View.GONE
                } else {
                    tvAuthor!!.visibility = View.VISIBLE
                    tvAuthor!!.text = articleItem.getAuthor()
                }
                tvPublishData?.setText(articleItem.publishdate_format)
            } else {
                findViewById<View>(R.id.layout_author).visibility = View.GONE
            }
            refreshBottomStyle(data.articleItem, 1)
            UserRecommend.addItemKeyWord(articleItem, this)
            if (!TextUtils.isEmpty(articleItem.real_title)) imageTitle!!.text =
                articleItem.real_title else imageTitle!!.text =
                articleItem.getTitle()
            readStatus()
            decideTitileBarStyle()
            AddMedalStatistics.addMedalStatistics(this) //勋章统计
            startAddIntegralCounter()
            setImages(data.articleItem)
        } else {
            fault(null)
        }
    }

    private fun startAddIntegralCounter() {
        AddIntegralCounter.start(this, TimeoutCallback {
            if (articleItem == null) {
                return@TimeoutCallback
            }
            Addintegral.addintegral(
                this@ImageNewsDetailActivity,
                articleItem.getId(),
                2,
                if ("1" == articleItem.movie.isStudyContent) "1" else "0",
                articleItem
            )
        })
    }

    override fun fault(data: Any?) {
        if (isFinishing || isDestroyed) {
            return
        }
        setImages(articleItem)
        if (null == data) {
            showStateView(TYPE_NO_CONTENT, false)
        } else {
            showStateView(TYPE_LOADING, false)
        }
    }


    /***
     * 功能：用线程保存图片
     *
     * @author wangyp
     */
    inner class SaveImage : AsyncTask<String?, Void?, String?>() {

        override fun doInBackground(vararg params: String?): String? {
            if (isFinishing() || isDestroyed()) {
                return null
            }
            var result = ""
            var inputStream: InputStream? = null
            var conn: HttpURLConnection? = null
            var outStream: FileOutputStream? = null
            try {
                val sdcard = Environment.getExternalStorageDirectory().toString()
                var file = File("$sdcard/Download")
                if (!file.exists()) {
                    file.mkdirs()
                }
                val SUFFIX = ".imgtype"
                file =
                    File(sdcard + "/Download/" + getResources().getString(R.string.tenantid) + "_" + Date().time + SUFFIX)
                val url = URL(params[0])
                conn = url.openConnection() as HttpURLConnection
                conn.requestMethod = "GET"
                conn!!.connectTimeout = 20000
                conn.doInput = true
                conn.connect()
                Log.e("", "==dow== " + conn.responseCode)
                if (conn.responseCode == 200) {
                    inputStream = conn.inputStream
                    val buffer = ByteArray(4096)
                    var len = 0
                    outStream = FileOutputStream(file)
                    while (inputStream.read(buffer).also { len = it } != -1) {
                        outStream.write(buffer, 0, len)
                    }
                    outStream.close()
                    var path = file.absolutePath
                    val fileType = FileFormatUtils.getType(path)
                    if (fileType == FileFormatUtils.FileType.GIF) {
                        path = path.replace(SUFFIX, ".gif")
                    } else if (fileType == FileFormatUtils.FileType.JPEG) {
                        path = path.replace(SUFFIX, ".jpg")
                    } else if (fileType == FileFormatUtils.FileType.PNG) {
                        path = path.replace(SUFFIX, ".png")
                    } else if (fileType == FileFormatUtils.FileType.BMP) {
                        path = path.replace(SUFFIX, ".bmp")
                    }
                    val renamedFile = File(path)
                    file.renameTo(renamedFile)
                    result = getResources().getString(R.string.image_besaved)
                    Utility.insertIntoMediaStore(
                        getApplicationContext(),
                        false,
                        renamedFile,
                        renamedFile.lastModified()
                    )
                } else {
                    result = getResources().getString(R.string.image_save_failed)
                }
            } catch (e: Exception) {
                result = getResources().getString(R.string.image_save_failed)
            } finally {
                try {
                    if (outStream != null) {
                        outStream.flush()
                        outStream.close()
                    }
                    inputStream?.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                conn?.disconnect()
            }
            return result
        }

        override fun onPostExecute(result: String?) {
            if (isFinishing() || isDestroyed()) {
                return
            }
            toastCenter(this@ImageNewsDetailActivity, result!!, false)
        }


    }

    override fun onStart() {
        super.onStart()
        if (articleItem != null) {
            val info = UserInfo.getUserInfo(this)
            AcquisitionManager.getInstance().readEnter(
                info,
                "" + articleItem.getId(),
                DomainUtil.getDomain(articleItem.getUrl()),
                articleItem.getUrl(),
                articleItem.getTitle(),
                articleItem.content
            )
        }
    }


    override fun onStop() {
        super.onStop()
        if (articleItem != null) {
            val info = UserInfo.getUserInfo(this)
            AcquisitionManager.getInstance().readExit(
                info,
                "" + articleItem.getId(),
                DomainUtil.getDomain(articleItem.getUrl()),
                articleItem.getUrl(),
                articleItem.getTitle(),
                articleItem.content
            )
        }
    }

    override fun getBarTextColorIsDefault(): Boolean {
        return false
    }
}